<template>
	<a-row>
		<a-form :layout="formLayout"  :form="form"  @submit="handleSubmit">
			<a-card title="基本信息" :bordered="true">
			    <a-row>
			     	<a-col  :lg='5'  :md='12'  :sm='24'>
						<a-form-item
							label="买方名称"
							>
							<a-input placeholder="请输入买方名称"  v-decorator="['name', baseform.name]" /> 
						</a-form-item> 
					</a-col>
					<a-col  :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
						<a-form-item   
							label="地址"
						>
							<a-input placeholder="请输入地址"  v-decorator="['address']"/> 
						</a-form-item>
				    </a-col>
				    <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='12'  :sm='24'>
						<a-form-item
							label="电话"
						>
							<a-input placeholder="请输入电话"   v-decorator="['phone']"/> 
						</a-form-item>
					</a-col>
					 <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
						<a-form-item
							label="邮箱"
						>
							<a-input placeholder="请输入邮箱"  v-decorator="['email']"/> 
						</a-form-item>

					</a-col>
				</a-row>
				<a-row>
			     	<a-col  :lg='5'  :md='12'  :sm='24'>
						<a-form-item
							label="网址"
							>
							<a-input placeholder="请输入网址"  v-decorator="['website']" /> 
						</a-form-item> 
					</a-col>
					<a-col  :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
						<a-form-item   
							label="行业"
						>
							<a-input placeholder="请输入"  v-decorator="['industry']"/> 
						</a-form-item>
				    </a-col>
				    <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='12'  :sm='24'>
						<a-form-item
							label="经营范围"
						>
							<a-input placeholder="请输入" v-decorator="['businessScope']"/> 
						</a-form-item>
					</a-col>
					 <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
						<a-form-item
							label="规模"
						>
							<a-input placeholder="请输入" v-decorator="['entSize']"/> 
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
			     	<a-col  :lg='5'  :md='12'  :sm='24'>
						<a-form-item
							label="联系人"
							>
							<a-input placeholder="请输入网址"  v-decorator="['contact']" /> 
						</a-form-item> 
					</a-col>
					<a-col  :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
						<a-form-item   
							label="联系人电话"
						>
							<a-input placeholder="请输入"  v-decorator="['mobile']"/> 
						</a-form-item>
				    </a-col>
				    
				</a-row>
			</a-card>
			<a-tabs  type="card"  :animated='true'   @change='tabChange'  style='margin: 28px 0;'>
			    <a-tab-pane tab="账户信息" key="1">
			    	<a-button type="dashed"  class='cursor  mt12  w100  mb20'  block  @click='addContact()' ><a-icon type="plus-circle" />添加</a-button>
			    	<a-table :columns="columns" :dataSource="bizBankAccounts" bordered  :pagination='false'  :rowKey="record => record.code">
			    		
					    <template v-for="col in ['bankName', 'bankAddress', 'accountName','bankAccount','swift','defaultFlag']" :slot="col" slot-scope="text, record, index">
					      <div :key="col">
					      	<!-- {{record.index}} 行数怎么确认？-->
					      	<template  v-if="record.editable  ">
					      		<a-radio-group   v-if="col=='defaultFlag'"  :value="record.defaultFlag"   @change="e => handleChangeContact(e.target.value, col, index)" > 
								      <a-radio value="1">是</a-radio> 
								      <a-radio value="0">否</a-radio> 
						    	</a-radio-group>
						         <a-input
						          v-else
						          style="margin: -5px 0"
						          :value="text"
						          
						          @change="e => handleChangeContact(e.target.value, col, index)"
						        />
					      	</template>
					        <template v-else>
					        	<span  v-if='col=="defaultFlag"'>{{text | commonRadio}}</span>
					        	<span  v-else>{{text}}</span>
					    	</template>
					      </div>
					    </template>
					    
					    <template slot="operation" slot-scope="text, record, index">
					      <div class='editable-row-operations'>
					        <span v-if="record.editable">
					        	<template  v-if='record.add'>
					        		<a   @click="() => addNewContact(index)"  class='color-blue'>添加</a>
					        		<a-divider type="vertical" />
							        <a-popconfirm title='Sure to delete?' @confirm="() => delContact(index)">
							            <a  class='color-red'>删除</a>
							        </a-popconfirm>
					        	</template>
					          	<template  v-else>
					          		<a  @click="() => saveContact(index)"  class='color-blue'>保存</a>
					          		<a-divider type="vertical" />
							        <a-popconfirm title='Sure to cancel?' @confirm="() => cancelContact(index)">
							            <a  class='color-red'>取消</a>
							        </a-popconfirm>
					          	</template>
					        </span>
					        <span v-else>
					          <a @click="() => editContact(index)"  class='color-blue'>编辑</a>
					          <a-divider type="vertical" />
					          <a-popconfirm title='Sure to delete?' @confirm="() => delContact(index)">
					            <a  class='color-red'>删除</a>
					          </a-popconfirm>
					        </span>

					      </div>
					    </template>
					</a-table>
			    </a-tab-pane>
			    <a-tab-pane tab="授信额度" key="3">
					<a-row>
				     	<a-col  :lg='5'  :md='12'  :sm='24'>
							<a-form-item
								label="授信总额度"
								>
								<a-input-group compact  >
								    <a-select  style="width: 30%"  v-decorator="['buyerCredit.creditLineUnit',baseform.buyerCredit.creditLineUnit]">
								      <a-select-option key="0">USD</a-select-option>
								      <a-select-option key="1">GBP</a-select-option>
								      <a-select-option key="2">EUR</a-select-option>
								      <a-select-option key="3">HKD</a-select-option>
								      <a-select-option key="4">CNY</a-select-option>
								    </a-select>
								    <a-input style="width: 60%"  v-decorator="['buyerCredit.creditLine',baseform.buyerCredit.creditLine]"/>
								</a-input-group>
							</a-form-item> 
						</a-col>
						<a-col  :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
							<a-form-item   
								label="已占用额度"
							>
								<a-input-group compact>
								    <a-select  style="width: 30%"  v-decorator="['buyerCredit.usedQuotaUnit',baseform.buyerCredit.usedQuotaUnit]">
								      <a-select-option key="0">USD</a-select-option>
								      <a-select-option key="1">GBP</a-select-option>
								      <a-select-option key="2">EUR</a-select-option>
								      <a-select-option key="3">HKD</a-select-option>
								      <a-select-option key="4">CNY</a-select-option>
								    </a-select>
								    <a-input style="width: 60%"   v-decorator="['buyerCredit.usedQuota',baseform.buyerCredit.usedQuota]"/>
								</a-input-group>
							</a-form-item>
					    </a-col>
					    <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='12'  :sm='24'>
							<a-form-item
								label="单笔最高额度"
							>
								<a-input-group compact>
								    <a-select style="width: 30%"   v-decorator="['buyerCredit.eachQuotaUnit',baseform.buyerCredit.eachQuotaUnit]">
								      <a-select-option key="0">USD</a-select-option>
								      <a-select-option key="1">GBP</a-select-option>
								      <a-select-option key="2">EUR</a-select-option>
								      <a-select-option key="3">HKD</a-select-option>
								      <a-select-option key="4">CNY</a-select-option>
								    </a-select>
								    <a-input style="width: 60%"  v-decorator="['buyerCredit.eachQuota',baseform.buyerCredit.eachQuota]"/>
								</a-input-group>
							</a-form-item>
						</a-col>
						 <a-col :xl="{ span: 5, offset: 1 }"  :lg='{ span : 5 ,offset:1}'  :md='{ span:11,offset:1}'  :sm='24'>
							<a-form-item
								label="授信有效期"
							>
								<a-date-picker   class='w-100'  v-decorator="['buyerCredit.creditValidityPeriod',baseform.buyerCredit.creditValidityPeriod]"  @change='changeShou'/>
							</a-form-item>
						</a-col>
					</a-row>
			    </a-tab-pane>
			</a-tabs>
			<!-- 隐藏域 -->
			<a-form-item  style='display: none;'>
				<a-input  v-decorator="['supOrBuyer', baseform.supOrBuyer]"  /> 
			</a-form-item>
			<a-form-item  style='display: none;'  v-if='isEdit == true'>
				<a-input  v-decorator="['code', baseform.code]"  /> 
			</a-form-item>
			<a-form-item  class='mt28'
				:wrapper-col="buttonItemLayout.wrapperCol"
			>
				<a-button type="primary"  html-type="submit"  class='mr20'>
					提交
				</a-button>
				<router-link to='/customer'>
				<a-button >
					取消
				</a-button></router-link>
			</a-form-item>
		</a-form>
	</a-row>
</template>

<script>
	import  { submitEnt,buyerDetail }  from  '@/api/buyer/index'
	import moment  from 'moment'
	/*联系人表格 columns*/
const columns = [{
  title: '银行名称',
  dataIndex: 'bankName',
  width: '15%',
  scopedSlots: { customRender: 'bankName' },
}, {
  title: '银行地址',
  dataIndex: 'bankAddress',
  width: '15%',
  scopedSlots: { customRender: 'bankAddress' },
}, {
  title: '账户名称',
  dataIndex: 'accountName',
  width: '15%',
  scopedSlots: { customRender: 'accountName' },
},
 {
  title: '账户',
  dataIndex: 'bankAccount',
  width: '15%',
  scopedSlots: { customRender: 'bankAccount' },
},  {
  title: 'SWIFT',
  dataIndex: 'swift',
  width: '15%',
  scopedSlots: { customRender: 'swift' },
}, {
  title: '是否设为默认',
  dataIndex: 'defaultFlag',
  width: '12%', 
  scopedSlots: { customRender: 'defaultFlag' },
},
{
  title: '操作',
  dataIndex: 'operation',
  scopedSlots: { customRender: 'operation' },
}]

export default {
  name: 'buyerAdd',
  data () {
  	// this.cacheData = this.bizBankAccounts.map(item => ({ ...item }))
    return {
    	/*form  布局*/
      	formLayout:'vertical',
	    baseform:{
	    	supOrBuyer:{ initialValue : 2},
	    	code:{initialValue:''},
      		name: { initialValue : '' , rules: [{ required: true, message: '请输入名称' },{ whitespace : true ,message:'当前输入不能为空'}]},
      		buyerCredit:{
      				creditLineUnit:{ initialValue : '0' },
					creditLine:{ initialValue : '' },

					usedQuota:{ initialValue : '' },
					usedQuotaUnit:{ initialValue : '0' },

					eachQuotaUnit:{ initialValue : '0' },
					eachQuota:{ initialValue : '' },
					creditValidityPeriod:{  },
      		},
      	},
		data:[],//*表格data
		bizBankAccounts:[],/*银行表 data*/
		
		cacheData:[],
      	columns,/*联系人表格 columns*/    
      	count : 0, 

      	isEdit:false,  
      	editData:[],                                                            
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
    
  },
  created(){
  	this.cacheData = this.bizBankAccounts.map(item => ({ ...item }))
 
  },
  mounted(){
  		let initpath = this.$route.path
	  	if(initpath == '/buyer/edit'){
	  			this.isEdit = true
	  			this.pageInit(this.$route.query.code)
	  	}
	  	else{
	  		this.isEdit = false
	  		this.baseform.code = ''
	  	}
  },
  methods:{
  	async pageInit(code){
  		await buyerDetail(code).then((res)=>{
  			if(res.data.flag == true){
  				let data = res.data.data
  				// console.log(data)
  				// this.form.setFieldsValue(data)
  				this.form.setFieldsValue({
			        supOrBuyer:'2',
	    			code:data.code,

      				name: data.name,
		      		address:data.address,
		      		phone:data.phone,
		      		email:data.email,
		      		website:data.website,
		      		industry:data.industry,
		      		businessScope:data.businessScope,
		      		entSize:data.entSize,
		      		contact:data.contact,
		      		mobile:data.mobile,
			      })
  				this.editData = data.buyerCredit

  				/*过滤账户表格其他信息*/
  				this.bizBankAccounts = data.bizBankAccounts.map(item => {
				    return {
				        accountName: item.accountName,
				        bankAccount: item.bankAccount, 
				        bankAddress: item.bankAddress, 
				        bankName: item.bankName, 
				        swift: item.swift, 
				        defaultFlag : item.defaultFlag
				    }
				})
  				// this.bizBankAccounts  = data.bizBankAccounts
  			}
  		})
  	},
  	/*提交表单*/
	handleSubmit (e) {
		let that = this , url
		e.preventDefault();
		// console.log(this.form.getFieldsValue())
		this.form.validateFields((err, values) => {
			if (!err) {
			  console.log('Received values of form: ', values);
			  values.bizBankAccounts = this.bizBankAccounts
			  if(that.isEdit == false){
			  	url = '/op/ent/create_ent'
			  }
			  else{
			  	url = '/op/ent/modify_ent'
			  }
			  
			  submitEnt(url,values).then((res)=>{
			  	if(res.data.flag == true){
			  		that.$message.success(res.data.msg)
			  		that.$router.push('/buyer')
			  	}
			  	else{
			  		that.$message.error(res.data.msg)
			  	}
			  	
			  })
			}
			else{
				console.log(err)
			}
		});
	},
		
	    // 联系人表格
	    addContact () {
	    this.count = this.bizBankAccounts.length
	      let newData  = {
	      		editable:true,
	      		add:true,
		        bankName:'',
		        bankAddress: '',
		        accountName: '',
		        bankAccount: '',
		        swift: '',
		        defaultFlag:'',
	      }
	      this.bizBankAccounts = [newData,...this.bizBankAccounts]
	    },
	    /*联系人值改变，更新data*/
	    handleChangeContact (value, column,index) {
	      const newData = [...this.bizBankAccounts]

	      // const target = newData.filter(item => key === item.key)[0]
	      // console.log(index,newData.filter((item,ind) => index === ind))
	      const target = newData.filter((item,ind) => index === ind)[0]
	      if (target) {
	        target[column] = value
	        this.bizBankAccounts = newData
	      }
	    },

	    editContact (index) {
	      const newData = [...this.bizBankAccounts]
	      const target = newData.filter((item,ind) => index === ind)[0]
	      if (target) {
	        target.editable = true
	        this.bizBankAccounts = newData//更新data中列的可编辑状态
	      }
	    },
	    saveContact ( index) {
	      const newData = [...this.bizBankAccounts]
	      const target = newData.filter((item,ind) => index === ind)[0]
	      if (target) {
	        delete target.editable
	        this.bizBankAccounts = newData
	        this.cacheData = newData.map(item => ({ ...item }))
	      }
	    },
	    addNewContact(index){
	    	const newData = [...this.bizBankAccounts]
			const target = newData.filter((item,ind) => index === ind)[0]
			if (target) {
				if(target.accountName =='' && target.bankAccount =='' && target.bankAddress == ''  &&  target.bankName==''  &&  target.swift == ''){
					return this.$message.warning('请输入信息！');
				}
				delete target.editable
				delete target.add
				this.bizBankAccounts = newData
				this.cacheData = newData.map(item => ({ ...item }))
			}
	    },
	    cancelContact (index) {
	      const newData = [...this.bizBankAccounts]
	      const target = newData.filter((item,ind) => index === ind)[0]
	      if (target) {
	        Object.assign(target, this.cacheData.filter((item,ind1) => index === ind1)[0])
	        delete target.editable
	        this.bizBankAccounts = newData
	      }
	    },
	    delContact(index){
	      const dataSource = [...this.bizBankAccounts]
	      this.bizBankAccounts = dataSource.filter((item,ind) => ind !== index)
	    },

    	tabChange(key){
    		if(key == 3){
    			if(this.isEdit == false){
    				this.baseform.buyerCredit.creditLineUnit.initialValue = '0'
    				this.baseform.buyerCredit.usedQuotaUnit.initialValue = '0'
    				this.baseform.buyerCredit.eachQuotaUnit.initialValue = '0'

    				// this.baseform.buyerCredit.creditValidityPeriod.initialValue = moment()
    			}
    			else{
    				if(this.editData == null){
    					return 
    				}
    				this.baseform.buyerCredit.creditLineUnit.initialValue = this.editData.creditLineUnit
    				this.baseform.buyerCredit.creditLine.initialValue = this.editData.creditLine

    				this.baseform.buyerCredit.usedQuota.initialValue = this.editData.usedQuota
    				this.baseform.buyerCredit.usedQuotaUnit.initialValue = this.editData.usedQuotaUnit

    				this.baseform.buyerCredit.eachQuotaUnit.initialValue = this.editData.eachQuotaUnit
    				this.baseform.buyerCredit.eachQuota.initialValue = this.editData.eachQuota

    				this.editData.creditValidityPeriod =  moment(this.editData.creditValidityPeriod)
    				this.baseform.buyerCredit.creditValidityPeriod.initialValue = this.editData.creditValidityPeriod
    				
    		
    		// 		this.$nextTick(()=>{

						// this.form.setFieldsValue({
						// 	buyerCredit:this.editData
								
					 //      });
				  // 	})
    			}
    			
    		}
    	},
	   
	    /*upload*/
	    handleChangeFile(info) {
	      if (info.file.status !== 'uploading') {
	        console.log(info.file, info.fileList);
	      }
	      if (info.file.status === 'done') {
	        this.$message.success(`${info.file.name} file uploaded successfully`);
	      } else if (info.file.status === 'error') {
	        this.$message.error(`${info.file.name} file upload failed.`);
	      }
	    },
	    changeShou(date,string){
	    	console.log(date,string)
	    }
  },
	computed: {
		
		buttonItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			wrapperCol: { span: 14, offset: 7 },
			} : {};
		},
		
	},
  components: {
    
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/*.ant-input{width: 200px;}*/
</style>
